package com.daka.tools;


import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * HTTP请求类
 */
public class HttpInvoker {

    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String APPLICATION_JSON = "application/json;charset=" + DEFAULT_CHARSET;
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

    /**
     * GET请求
     *
     * @param getUrl
     * @return 提取HTTP响应报文包体，以字符串形式返回
     * @throws IOException
     */
    public static String httpGet(String getUrl) throws IOException {
        URL getURL = new URL(getUrl);
        HttpURLConnection connection = (HttpURLConnection) getURL.openConnection();
        connection.connect();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sbStr = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sbStr.append(line);
        }
        bufferedReader.close();
        connection.disconnect();
        return new String(sbStr.toString().getBytes(), "utf-8");
    }

    /**
     * POST请求
     *
     * @param postUrl
     * @param postHeaders
     * @param postEntity
     * @return 提取HTTP响应报文包体，以字符串形式返回
     * @throws IOException
     */
    public static String httpPost(String postUrl, Map<String, String> postHeaders, String postEntity) throws IOException {

        URL postURL = new URL(postUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) postURL.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setInstanceFollowRedirects(true);
        httpURLConnection.setRequestProperty(" Content-Type ", " application/x-www-form-urlencoded ");

        if (postHeaders != null) {
            for (String pKey : postHeaders.keySet()) {

                httpURLConnection.setRequestProperty(pKey, postHeaders.get(pKey));
            }
        }
        if (postEntity != null) {
            DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
            out.writeBytes(postEntity);
            out.flush();
            out.close(); // flush and close
        }
        //connection.connect();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        StringBuilder sbStr = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sbStr.append(line);
        }
        bufferedReader.close();
        httpURLConnection.disconnect();
        return new String(sbStr.toString().getBytes(), "utf-8");
    }


    public static String httpPost1(String url, String param)
    {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try
        {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            String ctype = "application/json;charset=" + DEFAULT_CHARSET;
            conn.setRequestProperty("Content-Type", ctype);

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            //out = new PrintWriter(conn.getOutputStream());

            out = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_CHARSET);

            // 发送请求参数
            if (StringUtils.isNotEmpty(param))
                out.write(param);
            //out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            /*in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}*/

            //System.out.println("北航编码："+conn.getHeaderField("Content-Type"));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_CHARSET));
            StringBuilder sbStr = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                sbStr.append(line);
            }
            bufferedReader.close();
            result = sbStr.toString();
        } catch (Exception e)
        {
            System.out.println("param----------------->"+param);
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            } catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        System.out.println("http POST result---->" + result);
        return result;
    }

}
